#!/bin/bash

relation_name=$1

set -e

# Defaults
sprout_hostname=sprout.$(config-get zone)
hs_hostname=homestead.$(config-get zone):8888
hs_provisioning_hostname=homestead.$(config-get zone):8889
xdms_hostname=homer.$(config-get zone):7888
ralf_hostname=
sas_server=0.0.0.0
enum_server=
ellis_cookie_key=secret
ellis_api_key=$(hexdump -v -n 15 -e '1/1 "%02x"' /dev/random)

# Import existing configuration
[ ! -f /etc/clearwater/config ] || . /etc/clearwater/config

# Apply new configuration
home_domain=$(config-get zone)
[ "$relation-name" != "homestead-hss" ] || [ "$(relation-get public-address)" = "" ] || sprout_hostname=$(relation-get public-address)
[ "$relation-name" != "xdms" ] || [ "$(relation-get public-address)" = "" ] || xdms_hostname=$(relation-get public-address):9888
sas_server=$(config-get sas)
local_ip=$(unit-get private-address)
public_ip=$(unit-get public-address)
public_hostname=ellis-$(cut -d/ -f2 <<< $JUJU_UNIT_NAME).$(config-get zone)
smtp_smarthost=$(config-get smtp_server)
smtp_username=$(config-get smtp_username)
smtp_password=$(config-get smtp_password)
email_recovery_sender=$(config-get email_sender)
signup_key=$(config-get signup_key)

# Write configuration back
mkdir -p /etc/clearwater
cat >/etc/clearwater/config <<EOF
# Deployment definitions
home_domain=$home_domain
sprout_hostname=$sprout_hostname
hs_hostname=$hs_hostname
hs_provisioning_hostname=$hs_provisioning_hostname
xdms_hostname=$xdms_hostname
ralf_hostname=$ralf_hostname
sas_server=$sas_server
enum_server=$enum_server

# Local IP configuration
local_ip=$local_ip
public_ip=$public_ip
public_hostname=$public_hostname

# Email server configuration
smtp_smarthost=$smtp_smarthost
smtp_username=$smtp_username
smtp_password=$smtp_password
email_recovery_sender=$email_recovery_sender

# Keys
signup_key=$signup_key
ellis_cookie_key=$ellis_cookie_key
ellis_api_key=$ellis_api_key
EOF
